package Euler203;

import java.util.*;

import ReusableCode.MathFunctions;
import ReusableCode.PrimeFunctions;

public class Pascal {

	public static void main(String[] args) {
		List<long[]> pascal =  generatePascal(51);
		Map<Long, Boolean> distinct = new HashMap<Long, Boolean>();
		long sum = 0;
		
		for(int i = 0; i < pascal.size(); i++)
		{
			long row[] = pascal.get(i);
			
			for(int j = 0; j < (row.length/2)+1; j++)
			{
				distinct.put(row[j],true);
			}
		}
		
		Set<Long> keys = distinct.keySet();
		List<Integer> primes = PrimeFunctions.GetPrimes((int) Math.sqrt(Collections.max(keys)));
		Iterator<Long> iter = keys.iterator();
		while(iter.hasNext())
		{
			long val = iter.next();
			
			if(MathFunctions.isSquareFree(val, primes))
			{
				sum += val;
			}
		}	
		
		for(int i = 0; i < pascal.size(); i++)
		{
			long row[] = pascal.get(i);
			
			for(int j = 0; j < row.length; j++)
			{
				System.out.print(row[j] + " ");
			}
			
			System.out.println();
		}
		
		System.out.println(keys + "\nSum is: " + sum);
	}
	
	static List<long[]> generatePascal(int length)
	{
		List<long[]> pascals = new ArrayList<long[]>();
		
		for(int i = 0; i < length; i++)
		{
			long row[] = new long[i+1];
			long prev[] = new long[i+1]; 
			
			if(i>0)
			{
				prev = pascals.get(i-1);
			}
			
			for(int j = 0; j < i+1; j++)
			{
				if(j==0 || j==(row.length-1))
				{
					row[j] = 1;
				}
				else
				{
					row[j] = prev[j-1] + prev[j];
				}
			}
			
			pascals.add(row);
		}
		
		return pascals;
	}
}